package com.kx.kxpicture.controller;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.kx.kxpicture.annotation.AuthCheck;
import com.kx.kxpicture.common.BaseResponse;
import com.kx.kxpicture.common.DeleteRequest;
import com.kx.kxpicture.common.ResultUtils;
import com.kx.kxpicture.constant.UserLoginConstant;
import com.kx.kxpicture.exception.BusinessException;
import com.kx.kxpicture.exception.ErrorCode;
import com.kx.kxpicture.exception.ThrowsUtils;
import com.kx.kxpicture.manager.auth.SpaceUserAuthManager;
import com.kx.kxpicture.model.dto.picture.*;
import com.kx.kxpicture.model.dto.space.*;
import com.kx.kxpicture.model.entity.Picture;
import com.kx.kxpicture.model.entity.Space;
import com.kx.kxpicture.model.entity.User;
import com.kx.kxpicture.model.enums.PictureReviewStatusEnum;
import com.kx.kxpicture.model.enums.SpaceLevelEnum;

import com.kx.kxpicture.model.vo.SpaceVO;

import com.kx.kxpicture.service.SpaceService;
import com.kx.kxpicture.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 类功能描述
 *
 * @author kuangxin
 * date 2025/8/28
 */
@RestController
@RequestMapping("/space")
public class SpaceController {
    @Resource
    UserService userService;

    @Resource
    SpaceService spaceService;

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Resource
    SpaceUserAuthManager spaceUserAuthManager;

    @PostMapping("/add")
    public BaseResponse<Long> addSpace(@RequestBody SpaceAddRequest spaceAddRequest,HttpServletRequest httpServletRequest){
        long result = spaceService.addSpace(spaceAddRequest, userService.getLoginUser(httpServletRequest));
        return ResultUtils.success(result);

    }
    
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteSpace(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        Long id = deleteRequest.getId();

        Space oldSpace = spaceService.getById(id);
        ThrowsUtils.throwIf(oldSpace == null, ErrorCode.NOT_FOUND_ERROR);

        if (!oldSpace.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }

        boolean result = spaceService.removeById(id);
        ThrowsUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    @PostMapping("/update")
    @AuthCheck(mustRole = UserLoginConstant.USER_ADMIN)
    public BaseResponse<Boolean> updateSpace(@RequestBody SpaceUpdateRequest spaceUpdateRequest,
                                               HttpServletRequest httpServletRequest) {
        if (spaceUpdateRequest == null || spaceUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(httpServletRequest);

        Space space = new Space();
        BeanUtils.copyProperties(spaceUpdateRequest, space);
        //自动填充数据
        spaceService.fillSpaceBySpaceLevel(space);
        spaceService.validSpace(space,false);

        Long id = spaceUpdateRequest.getId();
        Space oldSpace = spaceService.getById(id);
        ThrowsUtils.throwIf(oldSpace == null, ErrorCode.NOT_FOUND_ERROR);
        boolean result = spaceService.updateById(space);
        ThrowsUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    @GetMapping("/get")
    @AuthCheck(mustRole = UserLoginConstant.USER_ADMIN)
    public BaseResponse<Space> getSpaceById(Long id, HttpServletRequest request) {
        ThrowsUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);

        Space space = spaceService.getById(id);
        ThrowsUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR);

        return ResultUtils.success(space);
    }

    @GetMapping("/get/vo")
    public BaseResponse<SpaceVO> getSpaceVOById(Long id, HttpServletRequest request) {
        ThrowsUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);

        Space space = spaceService.getById(id);
        ThrowsUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR);
        SpaceVO spaceVO = spaceService.getSpaceVO(space, request);
        User loginUser = userService.getLoginUser(request);
        List<String> permissionList = spaceUserAuthManager.getPermissionList(space, loginUser);
        spaceVO.setPermissionList(permissionList);
        return ResultUtils.success(spaceVO);
    }

    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserLoginConstant.USER_ADMIN)
    public BaseResponse<Page<Space>> listSpaceByPage(@RequestBody SpaceQueryRequest spaceQueryRequest) {
        long current = spaceQueryRequest.getCurrent();
        long size = spaceQueryRequest.getPageSize();

        Page<Space> spacePage = spaceService.page(new Page<>(current, size),
                spaceService.getQueryWrapper(spaceQueryRequest));
        return ResultUtils.success(spacePage);
    }

    @PostMapping("/list/page/vo")
    public BaseResponse<Page<SpaceVO>> listSpaceVOByPage(@RequestBody SpaceQueryRequest spaceQueryRequest,
                                                             HttpServletRequest request) {
        long current = spaceQueryRequest.getCurrent();
        long size = spaceQueryRequest.getPageSize();

        ThrowsUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);

        Page<Space> spacePage = spaceService.page(new Page<>(current, size),
                spaceService.getQueryWrapper(spaceQueryRequest));

        return ResultUtils.success(spaceService.getSpaceVOPage(spacePage, request));
    }



    @PostMapping("/edit")
    public BaseResponse<Long> editSpace(@RequestBody SpaceEditRequest spaceEditRequest, HttpServletRequest request) {
        if (spaceEditRequest == null || spaceEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        Space space = new Space();
        BeanUtils.copyProperties(spaceEditRequest, space);
        //自动填充数据
        spaceService.fillSpaceBySpaceLevel(space);
        space.setEditTime(new Date());
        spaceService.validSpace(space,false);
        User loginUser = userService.getLoginUser(request);

        Long id = spaceEditRequest.getId();
        Space oldSpace = spaceService.getById(id);
        ThrowsUtils.throwIf(oldSpace == null, ErrorCode.NOT_FOUND_ERROR);

        if (!oldSpace.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = spaceService.updateById(space);
        ThrowsUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(space.getId());
    }
    @GetMapping("/list/level")
    public BaseResponse<List<SpaceLevel>> listSpaceLevel() {
        List<SpaceLevel> spaceLevelList = Arrays.stream(SpaceLevelEnum.values())
                .map(spaceLevelEnum -> new SpaceLevel(
                        spaceLevelEnum.getValue(),
                        spaceLevelEnum.getText(),
                        spaceLevelEnum.getMaxCount(),
                        spaceLevelEnum.getMaxSize()))
                .collect(Collectors.toList());
        return ResultUtils.success(spaceLevelList);
    }


}
